package Service;

import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Server {
    private ServerSocket serverSocket;
    private Connection connection;

    // 存储客户端处理器的引用列表
    List<Socket> clientHandlers = new ArrayList<>();
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    public void start() {
        try {
            // 创建ServerSocket并监听指定端口
            serverSocket = new ServerSocket(8888);
            System.out.println("Server started. Listening on port " + 8888);

            // 连接到MySQL数据库
            String url = "jdbc:mysql://localhost:3306/gymmanagement";
            String user = "root";
            String dbPassword = "1234";
            connection = DriverManager.getConnection(url, user, dbPassword);
            if(connection!=null) System.out.println("成功");
            else System.out.println("失败");


            // 接受客户端连接并处理请求
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());

                System.out.println(clientSocket.getRemoteSocketAddress());
                // 创建处理线程
                ClientHandler clientHandler = new ClientHandler(clientSocket, connection);

//                // 将客户端处理器添加到引用列表中
//                clientHandlers.add(clientSocket);

                Thread thread = new Thread(clientHandler);
                thread.start();
            }
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭ServerSocket和数据库连接
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (IOException | SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
